

import 'package:h_flutter_119/utils/log_utils.dart';

typedef void EventCallBack(dynamic arg);

class EventBus{

  EventBus._internal();

  static final EventBus _singleton = EventBus._internal();

  factory EventBus() => _singleton;

  final _subscriptions = <String,List<Subscription>>{};

  /// 添加订阅者，返回一个 Subscription 对象，用于取消订阅
  Subscription on(String eventName,EventCallBack callBack){
    var subscription = Subscription(eventName, callBack);
    //存在key则返回value，查不到则返回 [] 不修改Map
    _subscriptions.putIfAbsent(eventName, () => []).add(subscription);
    return subscription;
  }

  /// 取消订阅（如果指定了 callback，则只取消对应的订阅者；否则取消所有订阅者）
  off(String eventName,[Subscription? subscription]){
    if(_subscriptions.containsKey(eventName)){
      if(subscription == null) {
        _subscriptions[eventName]?.clear();
      }else{
        _subscriptions[eventName]?.removeWhere((sub) => sub.eventCallBack == subscription.eventCallBack);
      }
    }
  }

  offAll(){
    _subscriptions.clear();
  }

  emit(String eventName,dynamic arg){
    if(_subscriptions.containsKey(eventName)) {
      for (var sub in _subscriptions[eventName]!) {
        sub.eventCallBack(arg);
      }
    }
  }

}

class Subscription{
  String eventName;
  EventCallBack eventCallBack;

  Subscription(this.eventName, this.eventCallBack);
}

//定义一个top-level（全局）变量，页面引入该文件后可以直接使用bus
var bus = EventBus();